﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;

namespace Kocic.RepositoryManagement.LinqToSql
{
    /// <summary>
    /// Defers all LINQ to SQL data object changes to the context and allows changes to be pushed to the context at once.
    /// </summary>
    /// <typeparam name="TContext">The data context to defer changes to.</typeparam>
    public class LinqToSqlContextDeferrer<TContext> : DataSourceDeferrer<TContext, Object>
        where TContext : DataContext, new()
    {
        /// <summary>
        /// Creates an instance of the EntityContextDeferrer class which uses a reference to the data context defined in the scope of a LinqToSqlExecutionContext instance.
        /// </summary>
        public LinqToSqlContextDeferrer()
            : base(LinqToSqlExecutionContext<TContext>.CurrentDataSource)
        {

        }

        /// <summary>
        /// Creates an instance of the LinqToSqlContextDeferrer class
        /// </summary>
        /// <param name="context">An instance of the data context to which to defer changes to</param>
        public LinqToSqlContextDeferrer(TContext context)
            : base(context)
        {
        }

        /// <summary>
        /// Disposes unmanaged resources.
        /// </summary>
        /// <param name="disposing">Value indicating if to invoke the method from the IDisposable.Dispose implementation or from the finalizer.</param>
        protected override void Dispose(Boolean disposing)
        {
            if (disposing)
            {
                if (this.Disposed)
                {
                    return;
                }

                try
                {
                    this.DataSource.SubmitChanges(ConflictMode.ContinueOnConflict);
                }
                catch (ChangeConflictException)
                {
                    foreach (ObjectChangeConflict o in this.DataSource.ChangeConflicts)
                    {
                        o.Resolve(RefreshMode.KeepChanges);
                    }
                }
                finally
                {
                    DeferralOperation = null;

                    base.Dispose(disposing);
                }
            }
        }
    }
}